package com.movie.controller.SysRateController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.movie.beans.*;
import com.movie.beans.base.AjaxResult;
import com.movie.beans.dto.RatingDto;
import com.movie.service.*;
import com.movie.utils.DateUtils;
import com.movie.utils.ShiroUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.movie.utils.RateUtil.getAvgRateAndPoint;

@Controller
@RequestMapping("/system/rate")
public class SysRateController {
    @Autowired
    private RateService rateService;
    @Autowired
    private MovieService movieService;
    @Autowired
    private UserService userService;
    @Autowired
    private SiteRateService siteRateService;
    @Autowired
    private OptionInfoService optionInfoService;

    private static String prefix = "/system/rate";
    @GetMapping()
    public String index(){
        return prefix+"/index";
    }

    @GetMapping("/crate")
    public String crate(){
        return prefix+"/crate";
    }

    @PostMapping("/rateList")
    @ResponseBody
    public Map rateList(int limit,int page,String userId,String rat){
        SysUser u = ShiroUtil.getSysUser();
        Rating rating = new Rating();
        if(u.isAdmin()){
            if(userId!=null&& !userId.equals(""))
            {
                rating.setUserId(Long.valueOf(userId));
            }
            else {
                rating.setUserId(null);
            }
            if(rat!=null&&rat!="")
            {
                rating.setRating(Double.valueOf(rat));
            }
            else
            {
                rating.setRating(null);
            }
        }
        else {
            rating.setUserId(u.getUserId());
            if(rat!=null&& !rat.equals(""))
            {
                rating.setRating(Double.valueOf(rat));
            }
            else
            {
                rating.setRating(null);
            }
        }
        Map map = new HashMap();
        PageHelper.startPage(page,limit);
        List<Rating> ratings = rateService.selectRatingList(rating);
        List<RatingDto> dtos = new ArrayList<>();
        for (Rating r: ratings) {
            RatingDto dto = new RatingDto();
            dto.setMovieId(r.getMovieId());
            dto.setRating( r.getRating());
            dto.setRatingId(r.getRatingId());
            dto.setTimestamp(r.getTimestamp());
            dto.setUserId(r.getUserId());

            Movies m = movieService.getMoviesById(r.getMovieId());
            if(m!=null){
                dto.setTitle(movieService.getMoviesById(r.getMovieId()).getTitle());
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式，不显示毫秒
            String str = df.format(r.getTimestamp());
            dto.setStrTime(str);
            dto.setUserName(userService.selectUserById(r.getUserId()).getLoginName());
            dtos.add(dto);
        }
        map.put("msg","");
        map.put("code",0);
        map.put("data",dtos);
        map.put("count",new PageInfo(ratings).getTotal());
        return map;
    }

    @PostMapping("/rate/{id}")
    @ResponseBody
    public AjaxResult rate(@PathVariable(value = "id") Long id,@RequestParam Double rate){
        SysUser user = ShiroUtil.getSysUser();
        Rating temp = new Rating();
        temp.setUserId(user.getUserId());
        temp.setMovieId(id);
        Rating r = rateService.selectRating(temp);
        if (r!=null){
            return AjaxResult.warn("已对该电影评分");
        }

        Rating rating = new Rating();
        rating.setMovieId(id);
        rating.setRating(rate);
        rating.setUserId(user.getUserId());
        Long startTs = System.currentTimeMillis();
        rating.setTimestamp(startTs);
        int i = rateService.insert(rating);
        if(i>0){

            OptionInfo optionInfo = new OptionInfo();
            optionInfo.setId(user.getUserId());
            optionInfo.setMovieId(id);
            optionInfo.setTime(DateUtils.getNowDate());
            optionInfo.setOption(rate.toString());
            optionInfoService.insert(optionInfo);

            Double avgRate = rateService.selectRatingAvgByMovieId(id);
            Double rate1 = getAvgRateAndPoint(avgRate)[0];
            Double realRate = getAvgRateAndPoint(avgRate)[1];
            Double point = getAvgRateAndPoint(avgRate)[2];
            SiteRate siteRate = new SiteRate(id,rate1,point,realRate);
            SiteRate is = siteRateService.selectSiteRateByMovieId(id);
            if(is!=null){
                siteRateService.update(siteRate);
            }
            else {
                siteRateService.insert(siteRate);
            }
            return AjaxResult.success("评分成功");
        }
        return AjaxResult.error("评分失败，请联系管理员");
    }
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult removerate(Rating rating){
        if(rateService.deleteRating(rating)>0)
        {
            return AjaxResult.error("删除成功");
        }
        return AjaxResult.error("评分失败，请联系管理员");
    }

}
